package com.knife.news.stat;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import com.knife.dbo.config.DBOConfig;

/**
 * 数据库工具类
 * 1，查找DataSource获取数据库连接
 * 2，释放连接资源
 */
public class DBHandle {
    /**
     * 获取数据库连接
     * 1，初始化上下文环境Context
     * 2，在Context中查找DataSource，名字预先给定，这里为：“java:comp/env/jdbc/stat”
     * 3，如果DataSource不为空，就从DataSource中取出一个连接
     */
    public synchronized static Connection getConn() throws Exception {
        Connection conn = null;
        /*DataSource ds = null;
        Context ctx = new InitialContext();
        ds = (DataSource) ctx.lookup("java:comp/env/jdbc/stat");
        if (ds != null) {
            conn = ds.getConnection();
        }*/
        conn = DBOConfig.getInstance().getDataSource().getConnection();
        return conn;
    }
    /**
     * 释放连接相关资源，请注意相关次序
     * 1，先释放结果集
     * 2，再释放语句句柄
     * 3，最后释放连接
     */
    public static void closeResource(Statement st, ResultSet rs, Connection cnn) {
        try {
            if (rs != null) {
                rs.close();
            }
        }
        catch (Exception es) {
            es.printStackTrace();
        }
        try {
            if (st != null) {
                st.close();
            }
        }
        catch (Exception es) {
            es.printStackTrace();
        }
        try {
            if (cnn != null) {
                cnn.close();
                cnn = null;
            }
        }
        catch (Exception es) {
            es.printStackTrace();
        }
    }

    /**
     * 使用DriverManager获取数据库连接
     */
    public static Connection getConnection() throws Exception {
		/*
		String driver = "org.gjt.mm.mysql.Driver";
        String urlString = "jdbc:mysql://localhost/stat";
        String user = "root";
        String pwd = "root";
        Class.forName(driver);
        Connection cnn = DriverManager.getConnection(urlString, user, pwd);
        */
        Connection cnn = DBOConfig.getInstance().getDataSource().getConnection();
        return cnn;
    }

}
